package gdufs.lkl.calculator;

import android.os.Bundle;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class FunctionCalculatorActivity extends AppCompatActivity {

    private TextView functionNameTextView;
    private TextView functionExpressionTextView;
    private LinearLayout parametersLayout;
    private TextView resultTextView;
    private CustomFunction function;
    private List<EditText> parameterEditTexts = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_function_calculator);

        // 初始化视图
        functionNameTextView = findViewById(R.id.textViewFunctionName);
        functionExpressionTextView = findViewById(R.id.textViewFunctionExpression);
        parametersLayout = findViewById(R.id.layoutParameters);
        resultTextView = findViewById(R.id.textViewResult);
        Button calculateButton = findViewById(R.id.buttonCalculate);

        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // 从Intent中获取函数ID
        long functionId = getIntent().getLongExtra("functionId", -1);
        if (functionId == -1) {
            Toast.makeText(this, "函数不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 从存储中获取函数
        FunctionStorage storage = new FunctionStorage(this);
        for (CustomFunction f : storage.getFunctions()) {
            if (f.getId() == functionId) {
                function = f;
                break;
            }
        }

        if (function == null) {
            Toast.makeText(this, "函数不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置函数信息
        functionNameTextView.setText(function.getName());
        functionExpressionTextView.setText("表达式: " + function.getExpression());

        // 动态创建参数输入框
        createParameterInputs();

        // 设置计算按钮点击事件
        calculateButton.setOnClickListener(v -> calculateResult());
    }

    private void createParameterInputs() {
        parametersLayout.removeAllViews();
        parameterEditTexts.clear();

        if (function.getParameters() == null || function.getParameters().isEmpty()) {
            return;
        }

        // 为每个参数创建输入框
        for (String param : function.getParameters()) {
            TextView labelView = new TextView(this);
            labelView.setText(getString(R.string.enter_parameter_value, param));
            labelView.setPadding(0, 16, 0, 0);
            parametersLayout.addView(labelView);

            EditText editText = new EditText(this);
            editText.setHint(param);
            parameterEditTexts.add(editText);
            parametersLayout.addView(editText);
        }
    }

    private void calculateResult() {
        try {
            // 收集参数值
            List<Double> paramValues = new ArrayList<>();
            for (EditText editText : parameterEditTexts) {
                String valueStr = editText.getText().toString().trim();
                if (valueStr.isEmpty()) {
                    Toast.makeText(this, "请输入所有参数", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    double value = Double.parseDouble(valueStr);
                    paramValues.add(value);
                } catch (NumberFormatException e) {
                    Toast.makeText(this, "参数必须是数字", Toast.LENGTH_SHORT).show();
                    return;
                }
            }

            // 计算结果
            double result = function.calculate(paramValues);

            // 显示结果，最多保留10位小数
            DecimalFormat df = new DecimalFormat("0.##########");
            resultTextView.setText(df.format(result));

        } catch (Exception e) {
            Toast.makeText(this, getString(R.string.calculation_error, e.getMessage()), Toast.LENGTH_SHORT).show();
            resultTextView.setText("错误");
        }
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
